package pre.liuxl.blog.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import com.baidu.aip.util.Util;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liuxuanlong on 2018/6/16.
 */
public class BaiduAiUtil {
    private static final Logger logger = LoggerFactory.getLogger(BaiduAiUtil.class);
    //设置APPID/AK/SK
    private static final String APP_ID = "11326033";
    private static final String API_KEY = "4VQe3G0ibthxzIbwgzORAfuQ";
    private static final String SECRET_KEY = "etGYqtyxETO8fQ03NqTdpamDPkLQTEnZ";

    public static void test(MultipartFile file) throws IOException, JavaLayerException {
        // 初始化一个AipSpeech
        AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
        // 调用接口
        org.json.JSONObject asrRes2 = client.asr(file.getBytes(), "wav", 16000, null);
        logger.info("识别出的文字:" + asrRes2.getJSONArray("result").get(0));
        String string = (String) asrRes2.getJSONArray("result").get(0);
        //拼接给图灵机器人接口发送的json数据
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        JSONObject jsonObject2 = new JSONObject();
        JSONObject jsonObject3 = new JSONObject();
        jsonObject1.put("text", string);
        jsonObject2.put("inputText", jsonObject1);
        jsonObject3.put("apiKey", "bc2ceb07827346f09e7577b62418bb1a");
        jsonObject3.put("userId", "272187");
        jsonObject.put("reqType", 0);
        jsonObject.put("perception", jsonObject2);
        jsonObject.put("userInfo", jsonObject3);
        List<String> stringList = new ArrayList<>();
        String result = JsonSMS(JSONObject.toJSONString(jsonObject), "http://openapi.tuling123.com/openapi/api/v2");
        logger.info("智能机器人回答结果" + result);
        JSONObject jsonResult = JSONObject.parseObject(result);
        JSONArray resultJSONArray = jsonResult.getJSONArray("results");
        for (int i = 0; i < resultJSONArray.size(); i++) {
            String str = resultJSONArray.getJSONObject(i).getJSONObject("values").getString("text");
            stringList.add(str);
            // 初始化一个AipSpeech
            AipSpeech client1 = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);

            // 调用接口
            TtsResponse res = client1.synthesis(str, "zh", 1, null);
            byte[] data = res.getData();

            org.json.JSONObject res1 = res.getResult();
            if (data != null) {
                try {
                    Util.writeBytesToFileSystem(data, "output.mp3");
                    File music = new File("E:\\blog", "output.mp3");
                    BufferedInputStream buffer = new BufferedInputStream(new FileInputStream(music));
                    Player player = new Player(buffer);
                    player.play();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (res1 != null) {
                logger.info("文字转为语音结果" + res1.toString(2));
            }
        }

    }

    public static String JsonSMS(String postData, String postUrl) {
        try {
            //发送POST请求
            URL url = new URL(postUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Length", "" + postData.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(postData);
            out.flush();
            out.close();
            //获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                logger.info("connect failed!");
                return "";
            }
            //获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return "";
    }

}
